# !/usr/bin/env python
# -*- coding: utf-8 -*-
# ///////////////////////////////////////////////////////////////
# @File    :   getImageAraeData.py
# @Time    :   2024/08/22 16:49:29
# @Author  :   kai.luo
# @Version :   1.0.0
# @Desc    :   拆分获取图片不同区域的数据
# ///////////////////////////////////////////////////////////////
import re
import traceback
from moudles.Common.common import *


def findProductStartPos(data: list):
    """
    查找项目开始的位置

    Args:
        data (list): _description_
    """
    findStdList = list()
    isSkip = False
    skip_num = 0
    pos_num = 0
    temp_product_start_post = list()
    error = '识别错误：识别错误：出现此问题的原因一般为：您上传了非正规化验单图片、上传的图片不完整或模糊'

    for item in data:
        pos_list, text_region_tuple = item
        leftTop_x, leftTop_y = pos_list[0]
        text_region = text_region_tuple[0]

        try:
            zh_len = re.findall(r'[\u4e00-\u9fff]', text_region.strip())  # 中文长度
            produt_name = re.findall(r'^项\s*[\u4e00-\u9fff]{0,5}', text_region.strip())  # 以‘项’目开始
            produt_name_2 = re.findall(r'[NOno]+项\s*[\u4e00-\u9fff]{0,5}', text_region.strip())  # 以‘项’目开始
            ch_en = re.findall(r'^英文\s*[\u4e00-\u9fff]{0,5}', text_region.strip())

            if len(zh_len) <= 5 and (produt_name or ch_en or produt_name_2):
                isSkip = True
                temp_product_start_post = pos_list[0]

            if isSkip:
                findStdList.append(text_region)
                skip_num += 1

                if skip_num > 7:
                    break
        except:
            print(traceback.print_exc())

    # 查找检查项目的标题
    for findStd in findStdList:
        std_name = re.findall(r'^项\s*[\u4e00-\u9fff]{0,5}', findStd.strip())  # 以‘项’目开始
        std_name_2 = re.findall(r'[NOno]+项\s*[\u4e00-\u9fff]{0,5}', findStd.strip())  # 以‘项’目开始
        std_ch_en = re.findall(r'^英文\s*[\u4e00-\u9fff]{0,5}', findStd.strip())

        if std_name or std_name_2 or std_ch_en:
            pos_num += 1
        elif re.findall(r'参考|测定值', findStd) or re.findall(r'^结果', findStd):
            pos_num += 1
        elif re.findall(r'^单位', findStd):
            pos_num += 1
        elif re.findall(r'^参考', findStd):
            pos_num += 1
    if pos_num == 4:
        return temp_product_start_post
    else:
        return error


def getImageBlockData(result, productStartPos, headerHeight, foortHeight, del_col_name_list, add_col_name_dict):
    """
    获取区块数据
    Args:
        result (_type_): 图片的数据
        productStartPos (_type_): 项目开始的位置
        headerHeight (_type_): 图片头部基本数据的高度
        foortHeight (_type_): 图片尾部数据的高度
        add_col_name_dict (_type_): 项目标题中需要过滤的列名称，去掉项目中不需要的项目
    Returns:
        _type_: _description_
    """
    # 初始化
    header_title_data_list = list()
    header_base_data_list = list()
    main_title_data_list = list()
    main_base_data_list = list()
    footer_data_list = list()

    productStart_Posx, productStart_Posy = productStartPos

    # 分离头部信息
    header_base_start_posy = productStart_Posy - headerHeight

    # 最后一个元素的Y轴坐标
    _, footer_end_posy = result[-1][0][0]
    footer_start_posy = footer_end_posy - foortHeight

    product_data_title_first_posy = float()
    product_data_title_flag = True
    # 纠正项目的起始位置
    fixed_productStart_Posy = productStart_Posy-float(6)
    for index, itemList in enumerate(result):
        entry_posx, pentry_posy = itemList[0][0]
        entry_text = itemList[1][0]

        if pentry_posy <= header_base_start_posy:
            header_title_data_list.append(itemList)
        elif pentry_posy > header_base_start_posy and pentry_posy < fixed_productStart_Posy:
            header_base_data_list.append(itemList)
        elif pentry_posy >= fixed_productStart_Posy and pentry_posy < footer_start_posy:
            # y 轴相差7以内，默认在一行
            if product_data_title_flag:
                if abs(pentry_posy-productStart_Posy) <= 7:
                    # del_col_name_list = ['提示', '标志', 'CT值']  # 去掉项目中不需要的项目
                    if entry_text not in del_col_name_list:
                        main_title_data_list.append(itemList)
                else:
                    product_data_title_flag = False
            else:
                main_base_data_list.append(itemList)
        else:
            footer_data_list.append(itemList)

    # 需要插入占位列名
    for k, v in add_col_name_dict.items():
        main_title_data_list.insert(k, v)

    return header_title_data_list, header_base_data_list, main_title_data_list, main_base_data_list, footer_data_list


def delNoMainLines(data: list):
    delNo_mainLines = []
    for indx, item in enumerate(data):
        if re.findall(r'^[0-9][0-9_-]*', item[0]):
            delNo_mainLines.append(item[1:])
        else:
            if len(item) > 2:
                delNo_mainLines.append(item)

    return delNo_mainLines


def getItemsWidth(data: list):
    """
    获取一维数组每行之间的宽度
    Args:
        data (list): _description_
    """
    items_width_list = list()
    item_posx = ''
    for indx, item in enumerate(data):
        x, y = item[0][0]
        if indx == 0:
            item_posx = x
        else:
            num = int(x)-int(item_posx)
            items_width_list.append(num)
            #
            item_posx = x

    return items_width_list


def getImageArea(data: list):
    """
    判断图片格式所属省市区域
    Args:
        data (list): _description_
    """

    chongqinAreas, sichuanAreas = getArea()

    area = []
    isSkip = False
    for index, entry in enumerate(data):
        if isSkip:
            break

        text = entry[1][0]

        if not isSkip:
            for chongqin_item in chongqinAreas:
                if chongqin_item in text:
                    if '金域医学' in text:
                        area = ['chongqin', 'kingmend']
                    elif '妇幼保健院' in text:
                        area = ['chongqin', 'maternalChildHospital']
                    else:
                        area = ['chongqin', 'other']
                    isSkip = True
                    break

        if not isSkip:
            for sichuan_item in sichuanAreas:
                if sichuan_item in text:
                    if '天府新区人民医院' in text:
                        area = ['sichuan', 'maternalChildHospital']
                    elif '南充市中心医院' in text:
                        area = ['sichuan', 'maternalChildHospital']
                    isSkip = True
                    break
        # 结束
        if index > 6:
            isSkip = True
    return area


def fixedLineList(data: list):
    """
    纠正无意义的符号参杂在一行列表中
    标志或者提示类的符号在中间参杂，如：(+)
    Args:
        data (list): _description_
    """
    new_data = list()
    for item in data:
        text = item[1][0]
        isDel = re.findall(r'[0-9a-zA-Z*]+|[\u4e00-\u9fff]+', text)
        # isDelCh = re.findall(r'[\u4e00-\u9fff]+', text)
        if isDel:
            new_data.append(item)

    return new_data


def getMaxLineList(max_len: int, data: list):
    """
    获取项目最长行的数据

    Args:
        data (list): _description_
    """
    max_line_list = []
    for index, line_list in enumerate(data):
        if max_len == len(line_list):
            for line in line_list:
                x, y = line[0][0]
                max_line_list.append(x)
            break

    return max_line_list
